using MediatR;
using Medical.Api.Write.Application.Command.BasicManagement.EquipmentPackageDictionaryCommand;
using Medical.Domain.BasicManagement;
using Medical.ErrorCode;
using Medical.Interstructrue.Base;

namespace Medical.Api.Write.Application.Handler.BasicManagement.EquipmentPackageDictionaryHandler
{
    /// <summary>
    /// 删除器械包处理器
    /// 处理器械包逻辑删除请求，将指定器械包标记为已删除状态
    /// </summary>
    public class DeleteEquipmentPackageHandler : IRequestHandler<DeleteEquipmentPackageCommand, ApiResult<bool>>
    {
        private readonly IBaseRepository<EquipmentPackage> _packageRepository;
        private readonly ILogger<DeleteEquipmentPackageHandler> _logger;

        /// <summary>
        /// 构造函数
        /// </summary>
        /// <param name="packageRepository">仓储</param>
        /// <param name="logger">日志记录器</param>
        public DeleteEquipmentPackageHandler(
            IBaseRepository<EquipmentPackage> packageRepository,
            ILogger<DeleteEquipmentPackageHandler> logger)
        {
            _packageRepository = packageRepository;
            _logger = logger;
        }

        /// <summary>
        /// 处理删除器械包请求
        /// </summary>
        /// <param name="request">删除器械包命令</param>
        /// <param name="cancellationToken">取消令牌</param>
        /// <returns>操作结果</returns>
        public Task<ApiResult<bool>> Handle(DeleteEquipmentPackageCommand request, CancellationToken cancellationToken)
        {
            try
            {
                // 根据ID查找器械包记录
                var package = _packageRepository.GetModel(request.Id);
                if (package == null)
                {
                    return Task.FromResult(new ApiResult<bool>
                    {
                        Code = ApiEnums.NotFound,
                        Msg = "器械包不存在",
                        Data = false
                    });
                }

                // 执行逻辑删除：将IsDeleted设为true
                package.IsDeleted = true;
                package.UpdateTime = DateTime.Now;

                var result = _packageRepository.Update(package) > 0;

                _logger.LogInformation("删除器械包 {Name}，ID: {Id}, 结果: {Result}",
                    package.PackageName, package.Id, result ? "成功" : "失败");

                return Task.FromResult(new ApiResult<bool>
                {
                    Code = result ? ApiEnums.Success : ApiEnums.Error,
                    Msg = result ? "器械包删除成功" : "器械包删除失败",
                    Data = result
                });
            }
            catch (Exception ex)
            {
                _logger.LogError(ex, "删除器械包时发生异常");
                return Task.FromResult(new ApiResult<bool>
                {
                    Code = ApiEnums.Error,
                    Msg = "删除器械包时发生错误",
                    Data = false
                });
            }
        }
    }
}